package ViewModel;

import android.app.Dialog;
import android.content.Context;
import android.databinding.ObservableInt;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.example.administrator.drinkdevice.BuildConfig;
import com.example.administrator.drinkdevice.R;

import org.json.JSONObject;

import java.io.PrintWriter;
import java.io.StringWriter;

import Const.PublicDefine;
import Factory.Factory;
import Helper.App;
import Helper.CommProtocol;
import Helper.Log;
import Interface.IAsynCallBackListener;
import Interface.ICommProtocol;
import Service.SysService;
import ServiceTask.IDownProgress;
import ServiceTask.UpdateManager;

public class AppUpdate_ViewMovel extends Base_ViewModel {
    private Dialog dialog;
    private String updateFileName;
    boolean clossUpdate = false;
    JSONObject jsonObject;
    final String[] filename = {""};
    private int upflag=0;
    private Context ctx;
    public AppUpdate_ViewMovel(Context base, Dialog dialog) {
        super(base);
        ctx = base;
        this.dialog = dialog;
        Title.Text.set("检查升级");
        UpLater.Text.set("以后再说");
        UpDate.Text.set("现在升级");

    }


    //在主线程里面处理消息并更新UI界面
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.obj instanceof IAsynCallBackListener) {
                ((IAsynCallBackListener) msg.obj).onFinish("", msg.arg1);
            }
        }
    };

    private Handler UpdateProgressHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Progress.set(msg.arg1);
            ProgressMax.set(msg.arg2);
        }
    };


    public final TextBind Title = new TextBind("");
    public final TextBind UPInfo = new TextBind("");
    public final ButtonBind UpLater = new ButtonBind("");
    public final ButtonBind UpDate = new ButtonBind("");
    public final ButtonBind Btn_Close = new ButtonBind("×");
    public final ObservableInt Progress = new ObservableInt(0);
    public final ObservableInt ProgressMax = new ObservableInt(0);

    /**
     * 是否显示
     */
    public final ObservableInt ProcessVisible = new ObservableInt(View.GONE);

    public void Btn_Close_Click(View view) {
        try {
            UpdateManager.DownCancel(filename[0]);
        }
        catch (Exception e)
        {

        }
        dialog.dismiss();
    }

    public void Update(View view) {
        try {
            view.setEnabled(false);
            UPInfo.Text.set("正在连接升级服务器...");
            CheckUpdate(getBaseContext());
            view.setEnabled(true);
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            Log.write("Exception",sw.toString());
            e.printStackTrace();
            view.setEnabled(true);
        }
    }

    public void UpdataBtn_Click(View view) {
        ProcessVisible.set(View.VISIBLE);
        UPInfo.Text.set("正在下载新版本...");
        UpDate.Visible.set(View.GONE);
        try {
            if (upflag==1)
            {
                DownAppFile(view);
                return;
            }
            if (upflag==3)
            {
                dialog.dismiss();
                return;
            }
            UpdateManager.DownFile(getBaseContext(), jsonObject.getJSONObject("JsonData").getString("DownUrl"),
                    false, new IDownProgress() {
                        @Override
                        public void DownProgress(final int fileSize, final int downLoad, String localFileName) {
                            filename[0] = localFileName;
                            final int fsize = fileSize;
                            final int downsize = downLoad;
                            Message upmsg = new Message();
                            upmsg.arg1=downsize;
                            upmsg.arg2=fsize;
                            UpdateProgressHandle.sendMessage(upmsg);

                            if (downLoad >= fileSize) {
                                Message msg = new Message();
                                msg.arg1 = 0;
                                msg.obj = new IAsynCallBackListener() {
                                    @Override
                                    public void onFinish(Object sender, Object data) {
                                        //UpdateDevice(filename[0]);
                                    }

                                    @Override
                                    public void onError(Object sender, Exception e) {

                                    }
                                };
                                mHandler.sendMessage(msg);
                            }
                        }
                    });
        } catch (Exception e) {

        }
    }

    public void DownAppFile(View view) {
        try {
            UPInfo.Text.set("正在下载升级文件");
            UpDate.Enabled.set(false);
            ProcessVisible.set(View.VISIBLE);

            UpdateManager.DownFile(getBaseContext(), jsonObject.getJSONObject("JsonData").getString("DownUrl"),
                    true, new IDownProgress() {
                        @Override
                        public void DownProgress(final int fileSize, final int downLoad, String localFileName) {
                            filename[0] = localFileName;
                            final int fsize = fileSize;
                            final int downsize = downLoad;
                            Message upmsg = new Message();
                            upmsg.arg1 = downsize;
                            upmsg.arg2 = fsize;
                            UpdateProgressHandle.sendMessage(upmsg);

                            if (downLoad >= fileSize) {

                            }
                        }
                    });

        } catch (Exception e) {

        }
    }

    /**
     * 检查升级
     */
    private void CheckUpdate(final Context ctx) throws Exception {

        ProcessVisible.set(View.GONE);
        UPInfo.Text.set("正在检查新版本...");
        String appName= App.getAppName(this);
        ICommProtocol commProtocol = Factory.GetInstance(CommProtocol.class, new Object[]{this});
        String url = String.format("%s/AppUpdate/UpdateVerify?appName=%s&CurrentVer=%d&deviceid=%08X&merchantId=%d&produceVer=%s&devicetype=%08X",
                PublicDefine.UpdateHost, appName, App.getVersionCode(this), SysService.DeviceID, PublicDefine.cinemaInfo.getString("id"), BuildConfig.VERSION_NAME, SysService.DeviceType);
        commProtocol.Get(
                url,
                new IAsynCallBackListener() {
                    @Override
                    public void onFinish(Object sender, Object data) {
                        try {
                            jsonObject = new JSONObject(data.toString());
                            if (jsonObject.getInt("Result")==0)
                            {
                                Message msg = new Message();
                                msg.arg1=1;
                                msg.obj=new IAsynCallBackListener(){
                                    @Override
                                    public void onFinish(Object sender, Object data) {
                                        try {
                                            UPInfo.Text.set(jsonObject.getJSONObject("JsonData").getString("Description"));
                                            UpDate.Enabled.set(true);
                                            UpDate.Visible.set(View.VISIBLE);
                                            upflag=1;
                                        } catch (Exception e){
                                            StringWriter sw = new StringWriter();
                                            e.printStackTrace(new PrintWriter(sw, true));
                                            Log.write("Exception",sw.toString());
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onError(Object sender, Exception e) {

                                    }
                                };
                                mHandler.sendMessage(msg);
                            }
                            else
                            {
                                Message msg = new Message();
                                msg.arg1=1;
                                msg.obj=new IAsynCallBackListener(){
                                    @Override
                                    public void onFinish(Object sender, Object data) {
                                        try {
                                            UPInfo.Text.set("已是最新版本，不用升级。");
                                            UpDate.Text.set("关闭");
                                            UpLater.Visible.set(View.GONE);
                                            upflag=3;
                                            UpDate.Enabled.set(true);
                                        }
                                        catch (Exception e)
                                        {

                                        }
                                    }

                                    @Override
                                    public void onError(Object sender, Exception e) {
                                        //viewModel.checkEnabled.set(true);
                                    }
                                };
                                mHandler.sendMessage(msg);

                            }
                        }
                        catch (Exception e)
                        {
                            StringWriter sw = new StringWriter();
                            e.printStackTrace(new PrintWriter(sw, true));
                            Log.write("Exception",sw.toString());
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Object sender, Exception e) {

                    }
                }

        );

    }
}
